<template>
  <div class="in-block">
    <div class="title">数据范化</div>
    <div class="hk-flex" style="margin-bottom:20px;">
      <el-form ref="form" style="flex:1;" :model="formData" :rules="rules" label-width="120px" label-position="left">
        <el-form-item prop="id" label="元数据">
          <el-cascader
            v-model="formData.id"
            filterable
            :options="options"
            :props="formDataProp"
            :show-all-levels="false"
            @change="(val)=>cascaderHandleChange(val,'change')"
          />
        </el-form-item>
      </el-form>
      <el-button type="primary" icon="el-icon-plus" size="mini" style="margin-top:0;" @click="handleAdd">新增字段</el-button>
    </div>
    <el-row :gutter="20" style="height: 100%">
      <el-col :span="24" style="height: 100%">
        <HkTable
          :table-data="rightTableData"
          :table-columns="rightTableLabel"
          :show-index="true"
          :operate="true"
          :show-pag="false"
          :table-height="80"
          :is-need-index="true"
        >
          <!--  字段值 -->
          <!-- <template #columnValue="scope">
            <el-tooltip placement="bottom" effect="light" :content="scope.row.row.columnValue">
              <div style="text-overflow:ellipsis;overflow:hidden;">
                {{ scope.row.row.columnValue }}
              </div>
            </el-tooltip>
          </template> -->
          <!--    数据类型      -->
          <template #columnType="scope">
            <span>{{ scope.row.row.columnType == 0 ? '原始数据' : '自定义' }}</span>
          </template>
          <!--     存储库字段名称     -->
          <template #metaName="scope">
            <el-select
              v-model="scope.row.row.metaName"
              placeholder="请选择"
              clearable
              filterable
              @change="handleEvent($event, scope.row)"
            >
              <el-option
                v-for="(item, childIndex) in metaNameList"
                :key="childIndex"
                :label="item.columnName"
                :value="item.id"
              />
            </el-select>
          </template>
          <!--    操作按钮      -->
          <template #operate="scope">
            <el-button
              v-if="scope.row.row.columnType == 1"
              :disabled="scope.row.index==notEditTbale.length"
              size="mini"
              type="text"
              @click="moveUp(scope.row, scope.row.index)"
            >上移
            </el-button>

            <el-button
              v-if="scope.row.row.columnType == 1"
              :disabled="scope.row.index == total - 1"
              size="mini"
              type="text"
              @click="moveDown(scope.row, scope.row.index)"
            >下移
            </el-button>
            <el-button v-if="scope.row.row.columnType == 1" type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.row.columnType == 1" type="text" @click="handleDel(scope.row)">删除</el-button>
          </template>
        </HkTable>
      </el-col>
    </el-row>

    <add-dialog
      ref="addDialogRef"
      :title="title"
      :product-code="productCode"
      :table-data="rightTableData"
      :context-list="contextList"
      :desc-list="descList"
      @handleSubmit="handleSave"
    />
  </div>
</template>

<script>
import HkTable from '@/components/Hk-Table/index'
import { getMetadataTreeList, getStoreTemplateColumn } from '@/api/milkyway/accessRules'
import AddDialog from '../../components/rule/ruleFieldEditor'
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'Step3',
  components: { HkTable, AddDialog },
  props: {
    tableData: {
      type: Array,
      default() {
        return []
      }
    },
    step3Data: {
      type: Object,
      default() {
        return {}
      }
    },
    dialogData: {
      type: Array,
      default() {
        return []
      }
    },
    isCheck: {
      type: Boolean,
      default() {
        return false
      }
    },
    importProduct: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      //  自定义 字段类型下拉框的数据
      contextList: [],
      //  描述$符下拉框的数据
      descList: [],
      notEditTbale: [],
      isEditTable: [],
      rightTableLabel: [
        { label: '解析字段名称', param: 'columnName' },
        { label: '解析字段值', param: 'columnValue' },
        { label: '数据类型', param: 'columnType', type: 'slot' },
        {
          label: '存储字段名称',
          param: 'metaName',
          type: 'slot',
          align: 'center'
        },
        { label: '存储字段描述', param: 'columnDesc' }
      ],
      rules: {
        id: [
          {
            type: 'array',
            required: true,
            message: '请选择元数据',
            trigger: 'change'
          }
        ]
      },
      metaNameList: [],
      leftTableLabel: [
        { label: '字段名称', param: 'columnName' },
        { label: '描述', param: 'columnDesc' }
      ],
      title: '新增',
      options: [],
      formDataProp: { value: 'id', label: 'mdName' },
      queryParams: {
        store: 0,
        metaData: '',
        typeId: '',
        dataType: 0
      },
      // 当前行的数据
      dataForm: {},
      // 第二步回显数据
      secondEchoData: {},
      // 点击编辑获取的当前弹窗数据
      currentDialogData: {},
      //   获取产品id
      productCode: '',
      newDialogEchoData: []
    }
  },
  computed: {
    // 总数
    total: {
      get() {
        return this.rightTableData.length
      }
    },
    formData: {
      get() {
        return this.step3Data
      }
    },
    dialogEchoData: {
      get() {
        return this.dialogData
      },
      set(val) {}
    },
    rightTableData: {
      get() {
        return this.tableData
      },
      set() {}
    }
  },
  watch: {
    importProduct: {
      async handler(newVal) {
        if (newVal.length > 0) {
          this.productCode = newVal[2]
          await this.handleJudgeType()
          this.getStoreTemplateColumn()
        }
      }
    },
    rightTableData: {
      handler(newVal) {
        if (newVal.length > 0) {
          this.notEditTbale = this.rightTableData.filter((i) => {
            return i.columnType == '0'
          })
          this.isEditTable = this.rightTableData.filter((i) => {
            return i.columnType == '1'
          })
          this.contextList = [...this.notEditTbale.map(i => { return { label: i.columnName, value: i.columnValue } }), ...this.isEditTable.map(i => { return { label: i.metaName, value: i.metaName } })]
          this.contextList = this.contextList.filter(i => i.label && i.label !== '')
          this.descList = [...this.notEditTbale.map(i => { return { label: i.columnName, value: i.columnValue } }), ...this.isEditTable.map(i => { return { label: i.metaName, value: i.columnValue } })]
          this.descList = this.descList.filter(i => i.label && i.label !== '')
        }
      },
      deep: true
    },
    dialogEchoData: {
      handler(newVal) {
        if (this.isEditTable.length > 0) {
          const oldDialogData = JSON.parse(JSON.stringify(newVal))
          this.isEditTable.forEach((i, index) => {
            const currentData = oldDialogData.filter(j => {
              return j.formData && i.columnName == j.formData.fieldName
            })
            if (currentData && currentData.length > 0) {
              this.newDialogEchoData[index] = currentData[currentData.length - 1]
            } else {
              this.newDialogEchoData[index] = { formData: { citeField: '自定义' }}
            }
          })
          console.log('监听rightTableData------获取的dialogData', this.newDialogEchoData)
        }
      }
    }
    /*    dialogEchoData: {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.rightTableData.forEach((i, index) => {
            const currentData = newVal.filter((j) => {
              return i.columnName === j.formData.fieldName
            })
            if (currentData && currentData.length > 0) {
              this.rightTableData[index].dialogData = currentData
            }
          })
        }
      }
    } */
  },

  async mounted() {
    await this.getMetadataTreeList()
    this.handleJudgeType()
    this.getStoreTemplateColumn()
  },
  methods: {
    //  判断存储数据标准第二项的值是什么类型
    handleJudgeType() {
      if (this.formData.id) {
        this.queryParams = {
          store: this.formData.id[0],
          metaData: this.formData.id[1]
        }
        //  取数据类型dataType :  标准日志 1 行为树 2 监测器 3  数据表  4
        const currentDatas = this?.options[0]?.children.filter((item) => {
          return item.id === this.formData.id[1]
        })
        if (currentDatas && currentDatas.length > 0) {
          this.queryParams.dataType = currentDatas[0].dataType
          if (currentDatas[0].dataType !== 2) {
            this.queryParams.typeId = this.importProduct[1]
          } else {
            this.queryParams.typeId = this.formData.id[2]
          }
        } else {
          this.queryParams.dataType = 0
          this.queryParams.typeId = ''
        }
      }
    },
    getRightTableData() {
      if (this.addData.length > 0) {
        this.addData.forEach((i) => {
          this.rightTableData.push(i)
        })
      }
      if (this.formData.id && this.formData.id.length === 0 && this.addDialogEchoData.length > 0) {
        this.addDialogEchoData.forEach((i) => {
          this.dialogEchoData.push(i)
        })
      }
    },
    /** 获取下拉框数据 */
    getMetadataTreeList() {
      return new Promise((resolve) => {
        getMetadataTreeList().then((res) => {
          this.options = res
          resolve(this.options)
        })
      })
    },
    /** 获取左侧列表数据 */
    getStoreTemplateColumn() {
      if (this.queryParams.metaData && this.queryParams.typeId && this.queryParams.typeId !== '') {
        getStoreTemplateColumn(this.queryParams).then((res) => {
          this.metaNameList = res
        })
      }
    },
    /** 级联选触发change事件 */
    cascaderHandleChange(value, type) {
      this.queryParams = {
        store: value[0],
        metaData: value[1]
      }
      //  切换清空存储库字段名称
      /*       this.rightTableData.forEach((item, index) => {
        item.metaName = undefined
        item.columnDesc = undefined
      }) */
      if (type) {
        this.handleJudgeType()
        this.getStoreTemplateColumn()
      }
    },
    /** 触发change事件 */
    handleChange(a, b) {
      const selectNode = this.list.filter((item) => {
        return a === item.columnName
      })
      this.noticeList[b].description = selectNode[0].description
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.isCheck) {
        this.title = '新增'
        this.$refs.addDialogRef.show('add')
      } else {
        this.$message.error('请先对数据进行解析')
      }
    },
    /** 触发事件 */
    handleEvent(value, row) {
      if (value) {
        const checkedData = this.metaNameList.filter((i) => {
          return i.id === value
        })
        this.rightTableData[row.$index].metaName = checkedData[0].columnName
        this.rightTableData[row.$index].columnDesc = checkedData[0].columnDesc
        this.changeValue()
      } else {
        this.rightTableData[row.$index].columnDesc = ''
      }
    },
    changeValue() {
      this.rightTableData = JSON.parse(JSON.stringify(this.rightTableData))
    },
    /** 弹窗点击保存返回的值 */
    handleSave(data) {
      const addList = {
        columnName: data.formData.fieldName,
        columnValue: data.formData.message || '',
        columnType: '1',
        columnConvert: data.formData.citeField == '自定义' ? '' : data.formData.citeField,
        ruleExpress: data?.dialogEchoDataRule?.ruleExpress || [],
        ruleMethodList: data?.ruleMethodList || []
      }
      if (data.isEdit) {
        this.rightTableData[data.editIndex].columnName = data.formData.fieldName
        this.rightTableData[data.editIndex].columnValue = data.formData.message || ''
        this.rightTableData[data.editIndex].columnConvert =
          data.formData.citeField === '自定义' ? '' : data.formData.citeField
        this.rightTableData[data.editIndex].ruleMethodList = data?.ruleMethodList || []
        this.rightTableData[data.editIndex].ruleExpress = data?.ruleExpress || []
        this.newDialogEchoData[data.editIndex - this.notEditTbale.length] = data
      } else {
        this.rightTableData.push(addList)
        this.newDialogEchoData.push(data)
      }
    },
    /** 校验必填项*/
    handleSubmit() {
      return new Promise((resolve, reject) => {
        this.$refs.form.validate((valid) => {
          if (valid) {
            resolve({
              mdId: this.formData.id,
              dataColumnRuleList: this.rightTableData,
              secondEchoData: {
                formData: this.formData,
                rightTableData: this.rightTableData,
                dialogEchoData: this.newDialogEchoData
              }
            })
            return true
          } else {
            this.$message.error('请完善表单')
            return false
          }
        })
      })
    },
    /** 删除按钮*/
    handleDel(scope) {
      this.rightTableData.splice(scope.index, 1)
      const delData = this.newDialogEchoData.filter((i) => {
        return scope.row.columnName != i.formData.fieldName
      })
      this.newDialogEchoData = delData
    },
    /** 编辑按钮 */
    handleEdit(scope) {
      this.title = '编辑'
      if (this.newDialogEchoData.length > 0) {
        const currentData = this.newDialogEchoData.filter((i) => {
          return i.formData.fieldName == scope.row.columnName
        })
        if (currentData.length > 0) {
          this.currentDialogData = currentData[0]
        } else {
          this.currentDialogData = { formData: { citeField: '自定义' }}
        }
        console.log('点击编辑按钮回显-------',this.currentDialogData);
        this.$refs.addDialogRef.show('edit', scope.index)
        this.$refs.addDialogRef.handleEchoData(this.currentDialogData)
      }
    },
    // 上移
    moveUp(row, idx) {
      const tableLost = this.rightTableData.splice(idx - 1, 1)
      this.rightTableData.splice(idx, 0, ...tableLost)
      const dialogLose = this.newDialogEchoData.splice(idx - this.notEditTbale.length - 1, 1)
      this.newDialogEchoData.splice(idx - this.notEditTbale.length, 0, dialogLose[0])
    },
    // 下移
    moveDown(row, idx) {
      const tableLost = this.rightTableData.splice(idx + 1, 1)
      this.rightTableData.splice(idx, 0, ...tableLost)
      const dialogLose = this.newDialogEchoData.splice(idx - this.notEditTbale.length + 1, 1)
      this.newDialogEchoData.splice(idx - this.notEditTbale.length, 0, dialogLose[0])
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-table{
  max-height:550px !important;
}
::v-deep .el-table__body-wrapper{
  min-height:400px !important;
}
::v-deep .hk-flex .el-form-item{
  margin-bottom:0 !important;
}
// ::v-deep .el-button {
//   margin-top:0 !important;
// }
::v-deep .el-tooltip span{
  text-overflow: ellipsis;
  overflow: hidden;
  display: block;
}
::v-deep .targetTable {
  // overflow: auto;
  height: 100%;
  // max-height:550px;
  .el-table{
    margin-top:0px !important;
  }
}
::v-deep .el-table .cell {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
}

</style>
